<?php

namespace App\Models;

use App\Jobs\SendTempMessage;
use App\Logic\ConfigLogic;
use App\User;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;

class Withdraw extends Model
{
    protected $table = 'withdraw';

    protected $guarded = [];

    const WX = 'wx';

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 添加提现
     * @param $user
     * @param $money
     * @param $ac_type
     * @param $ac_nickname
     * @param $ac_username
     * @return $this|bool|Model
     */
    public static function addWithdraw($user, $money, $ac_type, $ac_nickname, $ac_username)
    {
        $withdraw_min = config('withdraw_min', 5);
        if ($money < $withdraw_min) {
            return false;
        }
        \DB::beginTransaction();
        $wd = self::query()->create([
            'order_sn' => Uuid::uuid4()->getHex(),
            'user_id' => $user->id,
            'ac_type' => $ac_type,
            'ac_nickname' => $ac_nickname,
            'ac_username' => $ac_username,
            'money' => $money,
            'state' => 0,
            'log_id' => 0,
            'day' => date("Ymd", time())
        ]);
        if ($wd) {
            $log = MoneyLog::addLog($user, -$money, MoneyLog::WITHDRAW, '余额提现', self::class, $wd->id);
            if ($log) {
                $wd->log_id = $log->id;
                if ($wd->save()) {
                    \DB::commit();
                    //发送模板消息
                    return $wd;
                } else {
                    \DB::rollBack();
                    return false;
                }
            } else {
                \DB::rollBack();
                return false;
            }
        } else {
            \DB::rollBack();
            return false;
        }
    }

    public static function ckeck($id, $state, $remark)
    {
        $wd = self::query()->findOrFail($id);
        switch ($state) {
            case 1:
                return self::wx_remit($wd, $remark);
                break;
            case 2:
                return self::checkFail($wd, $remark);
                break;
            case 3:
                return self::checkFailAndRefund($wd, $remark);
                break;
            default:
                return [false, '状态异常'];
                break;
        }
    }

    public static function checkFail($wd, $remark)
    {
        if ($wd->state !== 0) {
            return [false, '当前提现状态不可拒绝'];
        }
        $wd->state = 2;
        $wd->remark = $remark;
        $wd->check_time = Carbon::now()->toDateTimeString();
        $wd->save();
        return [true, '提现已拒绝'];
    }

    public static function checkFailAndRefund($wd, $remark)
    {
        if (!in_array($wd->state, [0, 2])) {
            return [false, '当前提现状态不可退款'];
        }
        $log = MoneyLog::addLog($wd->user, $wd->money, MoneyLog::REFUND, '退款', self::class, $wd->id);
        if ($log) {
            $wd->state = 3;
            $wd->remark = $remark;
            $wd->check_time = Carbon::now()->toDateTimeString();
            $wd->re_log_id = $log->id;
            $wd->save();

            /*$temp_data = [
                'touser' => $wd->wx_user->open_id,
                'template_id' => '33Y5vTDwC3SC3p33KcltKJBATq1P0q7fRKed_kpWGnc',
                //'url' => '',
                'data' => [
                    'first' => '您有新的分销佣金到账
                        ',
                    'keyword1' => $name,
                    'keyword2' => $money,
                    'keyword3' => Carbon::now()->toDateTimeString(),
                    'remark' => '求知圈感谢有您的支持!'

                ],
            ];
            SendTempMessage::dispatch($temp_data);*/

            return [true, '提现已拒绝并退款'];
        } else {
            return [false, '退款失败'];
        }
    }


    public static function wx_remit($wd, $remark)
    {
        if ($wd->state !== 0) {
            return [false, '当前提现状态不可打款'];
        }
        if ($wd->ac_type !== self::WX) {
            return [false, '当前提现无法微信打款'];
        }

        $app = Factory::payment(ConfigLogic::getWxPayConfig());

        try {
            $res = $app->transfer->toBalance([
                'partner_trade_no' => $wd->order_sn,
                'openid' => $wd->ac_username,
                'check_name' => 'NO_CHECK',
                'amount' => $wd->money * 100,
                'desc' => config('wx_remit', '余额提现')
            ]);
            if ($res['result_code'] == 'SUCCESS') {
                $wd->state = 1;
                $wd->remark = $remark;
                $wd->check_time = Carbon::now()->toDateTimeString();
                $wd->save();
                return [true, '打款成功'];
            } else {
                return [false, '【商户平台错误】' . $res['err_code_des']];
            }
        } catch (\Exception $exception) {
            return [false, $exception->getMessage()];
        }


    }
}
